package Work;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class UserService {
    private final Map<String, User> userData = new HashMap<>();
    private static final String USER_DATA_FILE = "users.dat";

    public UserService() {
        loadUsers();
        // 初始化默认用户（管理员+普通用户）
        if (userData.isEmpty()) {
            userData.put("admin", new User("admin", "admin123", "ADMIN"));
            userData.put("user01", new User("user01", "user123", "USER"));
            saveUsers();
        }
    }

    // 加载用户数据
    private void loadUsers() {
        File file = new File(USER_DATA_FILE);
        if (!file.exists()) return;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            userData.putAll((Map<String, User>) ois.readObject());
        } catch (Exception e) {
            System.err.println("加载用户数据失败：" + e.getMessage());
        }
    }

    // 保存用户数据
    private void saveUsers() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(USER_DATA_FILE))) {
            oos.writeObject(userData);
        } catch (IOException e) {
            System.err.println("保存用户数据失败：" + e.getMessage());
        }
    }

    // 用户登录认证（返回User对象表示认证成功，null表示失败）
    public User login(String username, String password) {
        User user = userData.get(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }
}